<template>
  <Modal v-model="modelIsOpen" width="900" mask :closable="false">
    <template #footer>
      <Button size="default" @click="cancel" :loading="btnLoading">取消</Button>
      <Button type="primary" size="default" :loading="btnLoading" @click="ok"
        >确定</Button
      >
    </template>
    <Space direction="vertical" size="default" type="flex">
      <zz-Label :text="!readOnly ? '文件上传' : '文件查看'"></zz-Label>
      <Upload
        name="file"
        multiple
        type="drag"
        :action="'api/file/upload-file'"
        :show-upload-list="false"
        :accept="format.map((item) => '.' + item).join(',')"
        :format="format"
        :data="exData"
        :max-size="maxSize"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-progress="onProgress"
        :on-error="onError"
        class="upload-component"
        v-if="!readOnly"
      >
        <div style="padding: 20px 0">
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p>文件上传：请点击或拖拽文件！</p>
        </div>
      </Upload>
      <div style="height: 200px">
        <zz-Table
          :data="tableData"
          :hasPage="false"
          ref="zzTable"
          :loading="loading"
          :size="'mini'"
        >
          <vxe-table-column
            type="seq"
            title="序号"
            minWidth="60"
            align="center"
          ></vxe-table-column>
          <vxe-table-column
            title="文件名称"
            minWidth="60"
            field="fileName"
            align="center"
          ></vxe-table-column>
          <vxe-table-column title="操作" minWidth="60" align="center">
            <template v-slot="{ row }">
              <zz-TableBtn type="text" :loading="btnLoading" @click="show(row)"
                >查看</zz-TableBtn
              >
              <zz-TableBtn type="text" :loading="btnLoading" @click="down(row)"
                >下载</zz-TableBtn
              >
              <zz-TableBtn type="error" :loading="btnLoading" @click="del(row)"
                >删除</zz-TableBtn
              >
            </template>
          </vxe-table-column>
        </zz-Table>
      </div>
    </Space>
    <preview ref="preview"></preview>
  </Modal>
</template>

<script>
import { saveAs } from 'file-saver'
import { renderAsync } from 'docx-preview'
import preview from './components/preview.vue'
import config from '@/config'
export default {
  name: 'zzFile',
  emits: ['getFiles', 'delFile'],
  props: {
    readOnly: {
      type: Boolean,
      default: false,
    },
    format: {
      type: Array,
      default() {
        return ['jpg', 'jpeg', 'png', 'pdf', 'xlsx', 'xls', 'doc', 'docx']
      },
    },
    exData: {
      type: Object,
      default() {
        return {}
      },
    },
    maxSize: {
      type: Number,
      default() {
        return 500 * 1024
      },
    },
    fileList: {
      type: Array,
      default() {
        return []
      },
    },
    number: {
      type: Number,
    },
  },
  components: { preview },
  watch: {
    modelIsOpen: {
      async handler(newVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: false,
    },
  },
  data() {
    return {
      modelIsOpen: false,
      btnLoading: false,
      loading: false,
      tableData: [],
    }
  },
  methods: {
    init() {
      this.tableData = this.fileList
    },
    ok() {
      this.modelIsOpen = false
      this.reset()
      this.$emit('getFiles', this.tableData)
      console.log('getFiles回调成功')
    },
    async cancel() {
      // 調用接口批量刪除minio中已上傳的文件
      if (this.tableData.length > 0) {
        let map = this.tableData.map((e) => e.minioFileName)
        await this.$API.public.file.batchDeleteFiles.post(map)
      }
      this.modelIsOpen = false
      this.reset()
    },
    beforeUpload() {
      if (this.number) {
        if (this.tableData.length + 1 > this.number) {
          this.$Message.error('已超过规定上传数量')
          return false
        }
      }
    },
    onSuccess(res) {
      if (res.code == '01') {
        let item = { ...res.data }
        this.tableData.push(item)
      }
    },
    onProgress() {},
    onError() {},
    // 方案一：前端实现（目前只实现了docx）
    // async show(row) {
    //   let param = { fileName: row.minioFileName }
    //   let res = await this.$API.public.file.downFile.down(param)
    //   var blob = new Blob([res])
    //   this.$refs.preview.value = true
    //   // 测试预览
    //   let c = document.getElementsByClassName('preview-c')
    //   renderAsync(blob, c[0]).then((res) => {})
    // },
    // 方案二：后端实现
    async show(row) {
      let fileUrl = row.url
      window.open(
        config.FILE_VIEW_URL +
          '/onlinePreview?url=' +
          encodeURIComponent(this.$TOOL.crypto.BASE64.encrypt(fileUrl))
      )
    },
    async down(row) {
      let param = { fileName: row.minioFileName }
      let res = await this.$API.public.file.downFile.down(param)
      var blob = new Blob([res], {
        type: 'application/octet-stream',
      })
      await saveAs(blob, row.fileName)
    },
    async del(row) {
      this.$Modal.confirm({
        title: '是否删除?',
        content: '是否删除文件:' + row.fileName,
        onOk: async () => {
          let param = { fileName: row.minioFileName }
          let res = await this.$API.public.file.deleteFile.get(param)
          if (res.code == '01') {
            // minio删除完毕
            let index = this.tableData.findIndex(
              (e) => e.minioFileName === row.minioFileName
            )
            this.tableData.splice(index, 1)
            // 父页面业务回调
            this.$emit('delFile', row)
            console.log('delFile回调成功')
            this.$Message.success('删除成功')
          }
        },
      })
    },
    reset() {
      this.tableData = []
    },
  },
}
</script>

<style></style>
